package com.skyc.yunsuqianduan.controller;

import com.alipay.api.request.*;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.UUID;

import javax.annotation.Resource;
import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.AlipayRequest;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayOpenAuthTokenAppRequest;
import com.alipay.api.response.AlipayOpenAuthTokenAppResponse;
import com.skyc.yunsuqianduan.biz.UsersBiz;
import com.skyc.yunsuqianduan.model.Users;

@Controller
public class UsersController {
	
	@Resource
	private UsersBiz userbiz;
	
	private Users user;
	@ResponseBody
	@RequestMapping("/users/login")
	public HashMap<String, Object> login(Users user,HttpSession session){
		HashMap<String, Object> result=new HashMap<>();
		Users users = userbiz.findByUsernameAndPwd(user.getUserName(),user.getPwd());
		if(users!=null){
			session.setAttribute("user", users);
			return result;
		}else{
			result.put("msg", "账号或密码错误！");
			return result;
		}
		
		
	}
	
	@ResponseBody
	@RequestMapping("/users/yanzheng")
	public HashMap<String, Object> yanzheng (String userName){
		HashMap<String, Object> result=new HashMap<>();
		
		Users users = userbiz.findByUsername(userName);
		if(users!=null){
			result.put("error", "用户名已存在");
			return result;
		}else{
			return result;
		}
	}
	@ResponseBody
	@RequestMapping("/users/zhuce")
	public String zhuce (Users user){
			 userbiz.save(user);
			 return "success";
	}
	
//	@ResponseBody
//	@RequestMapping("/return_url")
//	public String zhifubaodenglu ( ServletRequest request,HttpSession session,HttpServletResponse response) throws AlipayApiException, IOException{
//		
//		response.reset();
//		PrintWriter out = response.getWriter();
//		 //获取支付宝GET过来反馈信息
//	    Map<String,String> params = new HashMap<String,String>();
//	    Map requestParams = request.getParameterMap();
//	    for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext();) {
//	        String name = (String) iter.next();
//	        String[] values = (String[]) requestParams.get(name);
//	        String valueStr = "";
//	        for (int i = 0; i < values.length; i++) {
//	            valueStr = (i == values.length - 1) ? valueStr + values[i]
//	                    : valueStr + values[i] + ",";
//	        }
//	        //乱码解决，这段代码在出现乱码时使用。如果mysign和sign不相等也可以使用这段代码转化
//	        valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
//	        params.put(name, valueStr);
//	    }
//	    
//	    //获取支付宝的通知返回参数，可参考技术文档中页面跳转同步通知参数列表(以下仅供参考)//
//	    //支付宝用户号
//	    String app_id = new String(request.getParameter("app_id").getBytes("ISO-8859-1"),"UTF-8");
//	    out.write(app_id + "\n");
//
//	    //获取第三方登录授权
//	    String alipay_app_auth = new String(request.getParameter("source").getBytes("ISO-8859-1"),"UTF-8");
//	    out.write(alipay_app_auth + "\n");
//	    
//	    //第三方授权code
//	    String app_auth_code = new String(request.getParameter("app_auth_code").getBytes("ISO-8859-1"),"UTF-8");//获的第三方登录用户授权app_auth_code
//	    out.write(app_auth_code + "\n");
//	    
//	    String privateKey = "MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQCR5SaxLwSA7GZeZaXdcBsx0hMLSjG95M9DeHkevodY2WDH+agxS+6kXqqr7KFd2VpjJpty4geLM6VSjmP4mH7gxDKYT3YEFqKqILzWRkV60UL9IjOD6ALFBJutPFS00ZAyh4qmdL9Z9t8EvvO9Oc6adUgLV9KNUuD1S7bimre1+z438wgivj1uAeByDZb7IzyZPeVwNzqC0Ur9wZWShhCthCFn8N5t8WhrWJ+upto4sA1xT/s7/2vYJc+S3PUqIKEkBWSF46F4YXWx3+C2uLdvlS62aLNzRvFbgQoh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Rtptch+3rxeBRPR1I6ikUo1CR9f64qs69yOT6wFX0AT8eRAoGBAIq4+vBhe3HFiezTvT+T6NWAk744q1Z78fZ8yq889/78edwQswEohskho3a8rP5u5CSUbupGNM5SPmqm5YC+bZpF2EQK72d84PuAu22M8OL/n/iQIgmGGeiobS98ldZvwyp9tTKLa1fUcM2b7iTF9+ccZ7NoPe+C7P0C7K+Wu+k5";
//	    String publicKey = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAqTG/GLr/F6nZ064cqZElM2Vji1LlFW7hGz7KfuCI4f8nf91PEaXzLm5MEIv0j5l7aLzdNKDOsV/XHZbt5H6S3lFtPKtfTioJevlS4+BiUd6a8TI3xrlryznz0fO3SXfEEkruoiBxBcl63avwdUdf6muJSwFNYWZFbU870UKvmlJedunPItPxN4t3fTV0S6T8ZXjv2maegLDAzHtGLK8500j4U9KeVzQu3YUJEGEfYbrhApJXl2egLz7cgOHvbTqp518Df1Dhhz5+aR7yRItoP5C7SzKBHvKsREBlCQSkrKxlrrCVz8EfHh8YBY7xZ4dxjs1VrTaWIcO/LDVFi8od/QIDAQAB";
//	    
//	    //使用auth_code换取接口access_token及用户userId
//	     AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do","2017083108475599",privateKey,"json","UTF-8",publicKey,"RSA2");//正常环境下的网关
//	     //AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipaydev.com/gateway.do","2016081500252664",privateKey,"json","UTF-8",publicKey,"RSA2");//沙箱下的网关
//	     
//	     
//	    AlipayOpenAuthTokenAppRequest requestLogin1 = new AlipayOpenAuthTokenAppRequest();
//	    requestLogin1.setBizContent("{" +
//	        "\"grant_type\":\"authorization_code\"," +
//	        "\"code\":\""+ app_auth_code +"\"" +
//	        "}");
//	    
//	    //第三方授权
//	    AlipayOpenAuthTokenAppResponse responseToken = alipayClient.execute(requestLogin1);
//	    if(responseToken.isSuccess()){
//	        out.write("<br/>调用成功" + "\n");
//	        
//	        out.write(responseToken.getAuthAppId() + "\n");
//	        out.write(responseToken.getAppAuthToken() + "\n");
//	        out.write(responseToken.getUserId() + "\n");
//	        String name=responseToken.getUserId().trim();
//	        System.out.print("获取的支付宝id="+name+"值");
//	        if(name==null||name==""){
//	        	name = UUID.randomUUID().toString();
//	        	System.out.print("自动生成的name"+name);
//	        }
//	        user = userbiz.findByUsername("name");
//	        	
//	        
//	        if(user!=null ){
//				session.setAttribute("user", user);
//				return "index";
//	        }else{
//	        
//	       	session.setAttribute("user", user);
//	       	return "index";
//	        }
//	       	
//	    } else {
//	        out.write("调用失败" + "\n");
//	        return "";
//	    }
//	    
//	   
	    
	    
	    //获的第三方登录用户授权auth_code
	//   String auth_code = new String(request.getParameter("auth_code").getBytes("ISO-8859-1"),"UTF-8");
//	    out.write(auth_code + "\n");
	    
	    
	    //获取用户信息授权
//	    AlipaySystemOauthTokenRequest requestLogin2 = new AlipaySystemOauthTokenRequest();
//	    requestLogin2.setCode(auth_code);
//	    requestLogin2.setGrantType("authorization_code");
//	    try {
	// AlipaySystemOauthTokenResponse oauthTokenResponse = alipayClient.execute(requestLogin2);
	// out.write("<br/>AccessToken:"+oauthTokenResponse.getAccessToken() + "\n");
	 
	   //调用接口获取用户信息
	// AlipayClient alipayClientUser = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do", "2016073100131450", privateKey, "json", "UTF-8", publicKey, "RSA2"); 
	// AlipayUserInfoShareRequest requestUser = new AlipayUserInfoShareRequest();
	// try {
//	     AlipayUserInfoShareResponse userinfoShareResponse = alipayClient.execute(requestUser, oauthTokenResponse.getAccessToken());
//	    out.write("<br/>UserId:" + userinfoShareResponse.getUserId() + "\n");//用户支付宝ID
//	     out.write("UserType:" + userinfoShareResponse.getUserType() + "\n");//用户类型
//	     out.write("UserStatus:" + userinfoShareResponse.getUserStatus() + "\n");//用户账户动态
//	     out.write("Email:" + userinfoShareResponse.getEmail() + "\n");//用户Email地址
//	     out.write("IsCertified:" + userinfoShareResponse.getIsCertified() + "\n");//用户是否进行身份认证
//	     out.write("IsStudentCertified:" + userinfoShareResponse.getIsStudentCertified() + "\n");//用户是否进行学生认证
	// } catch (AlipayApiException e) {
	     //处理异常
//	     e.printStackTrace();
	// }
	// } catch (AlipayApiException e) {
	     //处理异常
//	     e.printStackTrace();
	// }

		
//	}
	
	
	
		
	
	@InitBinder    
	public void initBinder(WebDataBinder binder) {    
	        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");    
	        dateFormat.setLenient(false);    
	        binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));    
	}  
	
		
	
	
	}

